package com.cn.mmd.controller;

import com.cn.mmd.model.*;
import com.cn.mmd.service.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/10 0010.
 */
@Controller
@RequestMapping(value = "page/shiro")
public class LoginController {


    @Autowired
    private StudentAppService studentAppService;

    @Autowired
    private TeacherDataLService teacherDataLService;

    @Autowired
    private LogController logController;

    @Autowired
    private ShiroUserRoleService shiroUserRoleService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private LeadershipService leadershipService;

    @Autowired
    private StudentIntegralController studentIntegralController;


    @RequestMapping(value = "/login")
    public synchronized String login(HttpServletRequest request) {
        String id = request.getParameter("username");
        String password = request.getParameter("password");
        Subject curUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(id, DigestUtils.md5Hex(password));
        token.setRememberMe(true);
        try {
            curUser.login(token);
            Session session = curUser.getSession();
            System.out.println(session.getId());
            if (request.getSession().getAttribute("user") != null) {
                return "index";
            }
            TeacherData teacherData = teacherDataLService.selectByPrimaryKey(id);
            logController.logManage("管理员" + id + "登录", id);
            request.getSession().setAttribute("user", teacherData);
            return "index";
        } catch (AuthenticationException e) {
            System.out.println("登录失败错误信息:" + e);
            token.clear();
            return "login";
        }

    }

    @RequestMapping(value = "/loginStudent")
    @ResponseBody
    public synchronized Object loginStudent(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String id = request.getParameter("username");
        String password = request.getParameter("password");
        StudentApp studentApp;
        studentApp = studentAppService.selectByPrimaryKey(id);
        if (studentApp != null) {
            Subject curUser = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(id, DigestUtils.md5Hex(password));
            token.setRememberMe(true);
            try {
                curUser.login(token);
                objectMap.put("token", DigestUtils.md5Hex(studentApp.getStudentid() + studentApp.getStudentpassword()));
                objectMap.put("code", 200);
                objectMap.put("message", "成功");
                objectMap.put("studentId", studentApp.getStudentid());
                objectMap.put("studentName", studentApp.getStudentname());
                Student student =  studentService.selectByPrimaryKey(id);
                objectMap.put("studentClass",student.getStudentclass());
                if (studentIntegralController.addIntegral(id, "login", 1) != null) {
                    objectMap.put("integral", "每日登陆积分加+1");
                } else {
                    objectMap.put("integral", "0");
                }
                logController.logStudent(id + "-" + studentApp.getStudentname() + ":登录了学生端", id);
            } catch (AuthenticationException e) {
                token.clear();
                objectMap.put("code", 201);
                objectMap.put("message", "登录失败密码错误");
            }
        } else {
            objectMap.put("code", 202);
            objectMap.put("message", "没有此角色");
        }
        return objectMap;
    }

    @RequestMapping(value = "/loginTeacher")
    @ResponseBody
    public synchronized Object loginTeacher(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String id = request.getParameter("username");
        String password = request.getParameter("password");
        TeacherData teacherData;
        teacherData = teacherDataLService.selectByPrimaryKey(id);
        if (teacherData != null) {
            Subject curUser = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(id, DigestUtils.md5Hex(password));
            token.setRememberMe(true);
            try {
                curUser.login(token);
                objectMap.put("code", 200);
                objectMap.put("message", "成功");
                objectMap.put("token", DigestUtils.md5Hex(teacherData.getTeacherid() + teacherData.getTeacherpassword()));
                objectMap.put("teacherId", teacherData.getTeacherid());
                objectMap.put("teacherName", teacherData.getTeachername());
                logController.logTeacher(id + ":登录了教师端", id);
            } catch (AuthenticationException e) {
                token.clear();
                objectMap.put("code", 201);
                objectMap.put("message", "登录失败密码错误");
            }
        } else {
            objectMap.put("code", 202);
            objectMap.put("message", "没有此角色");
        }
        return objectMap;
    }

    @RequestMapping(value = "/loginLead")
    @ResponseBody
    public synchronized Object loginLead(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        Map<String, Object> objectMap1 = new HashMap<String, Object>();
        String id = request.getParameter("username");
        String password = request.getParameter("password");
        TeacherData teacherData;
        teacherData = teacherDataLService.selectByPrimaryKey(id);
        if (teacherData != null) {
            ShiroUserRole shiroUserRole = new ShiroUserRole();
            shiroUserRole.setUserId(id);
            shiroUserRole.setRoleId(5);
            shiroUserRole = shiroUserRoleService.selectByAll(shiroUserRole);
            ShiroUserRole shiroUserRole1 = new ShiroUserRole();
            shiroUserRole1.setUserId(id);
            shiroUserRole1.setRoleId(6);
            shiroUserRole1 = shiroUserRoleService.selectByAll(shiroUserRole1);
            ShiroUserRole shiroUserRole2 = new ShiroUserRole();
            shiroUserRole2.setUserId(id);
            shiroUserRole2.setRoleId(7);
            shiroUserRole2 = shiroUserRoleService.selectByAll(shiroUserRole2);

//            String explain="教师发布";
            List<String> list = new ArrayList<String>();
            List<String> questionnaireExplains = leadershipService.selectQuestionnaireExplain();//到这里！！！加问卷类型！
            if (questionnaireExplains.size() > 0) {
                for (String questionnaireExplain : questionnaireExplains) {
                    System.out.println(questionnaireExplain);
                    if (questionnaireExplain.equals("教师发布") || questionnaireExplain.equals("SCL-90") || questionnaireExplain.equals("") || questionnaireExplain == null) {

                    } else {
                        list.add(questionnaireExplain);
                    }
                }
            }

            objectMap1.put("questionnaireExplains", list);

            if (shiroUserRole != null || shiroUserRole1 != null || shiroUserRole2 != null) {

                Subject curUser = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(id, DigestUtils.md5Hex(password));
                token.setRememberMe(true);
                try {
                    curUser.login(token);
                    objectMap.put("code", 200);
                    objectMap.put("message", "成功");
                    if (shiroUserRole != null) {//校长
                        List<Student> studentList = studentService.selectCollegeByAll();//获取学院
                        List<Map> mapList1 = new ArrayList<Map>();
                        if (studentList != null && studentList.size() > 0) {
                            Student student;
                            for (int i = 0; i < studentList.size(); i++) {
                                Map<String, Object> map1 = new HashMap<String, Object>();
                                Map<String, Object> map2 = new HashMap<String, Object>();
                                List<Map> mapList2 = new ArrayList<Map>();
                                student = studentList.get(i);
                                List<Student> studentList1 = studentService.selectMajorByAll(student.getStudentcollege());//获取和学院相关专业
                                if (studentList1 != null && studentList1.size() > 0) {
                                    Student student1;
                                    for (int j = 0; j < studentList1.size(); j++) {
                                        Map<String, Object> map3 = new HashMap<String, Object>();
                                        student1 = studentList1.get(j);
                                        map3.put("majorName", student1.getStudentmajor());
                                        mapList2.add(map3);
                                    }
                                }
                                map2.put("majorList", mapList2);
                                map2.put("collegeName", student.getStudentcollege());
                                map1.put("college", map2);
                                mapList1.add(map1);
                            }
                            objectMap1.put("collegeList", mapList1);
                        } else {
                            objectMap1.put("collegeList", mapList1);
                        }
//-----------------------------
//                        List<Course> courseList = courseService.selectCollegeC();//获取开课学院
//                        List<Map> mapList3 = new ArrayList<Map>();
//                        if (courseList != null && courseList.size() > 0) {
//                            Course course;
//                            for (int i = 0; i < courseList.size(); i++) {
//                                Map<String, Object> map3 = new HashMap<String, Object>();
//                                Map<String, Object> map4 = new HashMap<String, Object>();
//                                List<Map> mapList4 = new ArrayList<Map>();
//                                course = courseList.get(i);
//                                List<Course> courseList1 = courseService.selectCourseByCollegeC(course.getCoursecollege());
//                                if (courseList1 != null && courseList1.size() > 0) {
//                                    Course course1;
//                                    for (int j = 0; j < courseList1.size(); j++) {
//                                        Map<String, Object> map5 = new HashMap<String, Object>();
//                                        course1 = courseList1.get(j);
//                                        map5.put("courseName", course1.getCoursename());
//                                        map5.put("courseId", course1.getCourseid());
//                                        mapList4.add(map5);
//                                    }
//                                }
//                                map3.put("courseList", mapList4);
//                                map3.put("courseCollegeName", course.getCoursecollege());
//                                map4.put("courseCollege", map3);
//                                mapList3.add(map4);
//                            }
//                            objectMap1.put("course", mapList3);
//                        } else {
//                            objectMap1.put("course", mapList3);
//                        }
                        objectMap.put("data", objectMap1);
                        objectMap.put("roleId", shiroUserRole.getRoleId());
                        objectMap.put("token", DigestUtils.md5Hex(teacherData.getTeacherid() + teacherData.getTeacherpassword() + shiroUserRole.getRoleId()));
                    } else if (shiroUserRole1 != null) {//院长
                        Map<String, Object> map1 = new HashMap<String, Object>();
                        Map<String, Object> map2 = new HashMap<String, Object>();
                        List<Map> mapList2 = new ArrayList<Map>();
                        List<Map> mapList1 = new ArrayList<Map>();
                        Teacher teacher = teacherService.selectByPrimaryKeyo(id);
                        List<Student> studentList1 = studentService.selectMajorByAll(teacher.getTeachercollege());//获取和学院相关专业
                        if (studentList1 != null && studentList1.size() > 0) {
                            Student student1;
                            for (int j = 0; j < studentList1.size(); j++) {
                                Map<String, Object> map3 = new HashMap<String, Object>();
                                student1 = studentList1.get(j);
                                map3.put("majorName", student1.getStudentmajor());
                                mapList2.add(map3);
                            }
                        }
                        map2.put("majorList", mapList2);
                        map2.put("collegeName", teacher.getTeachercollege());
                        map1.put("college", map2);
                        mapList1.add(map1);
                        objectMap1.put("collegeList", mapList1);
//-----------------------------
//                        List<Course> courseList = courseService.selectCollegeC();//获取开课学院
//                        List<Map> mapList3 = new ArrayList<Map>();
//                        if (courseList != null && courseList.size() > 0) {
//                            Course course;
//                            for (int i = 0; i < courseList.size(); i++) {
//                                Map<String, Object> map3 = new HashMap<String, Object>();
//                                Map<String, Object> map4 = new HashMap<String, Object>();
//                                List<Map> mapList4 = new ArrayList<Map>();
//                                course = courseList.get(i);
//                                List<Course> courseList1 = courseService.selectCourseByCollegeC(teacher.getTeachercollege());
//                                if (courseList1 != null && courseList1.size() > 0) {
//                                    Course course1;
//                                    for (int j = 0; j < courseList1.size(); j++) {
//                                        Map<String, Object> map5 = new HashMap<String, Object>();
//                                        course1 = courseList1.get(j);
//                                        map5.put("courseName", course1.getCoursename());
//                                        map5.put("courseId", course1.getCourseid());
//                                        mapList4.add(map5);
//                                    }
//                                }
//                                map3.put("courseList", mapList4);
//                                map3.put("courseCollegeName", course.getCoursecollege());
//                                map4.put("courseCollege", map3);
//                                mapList3.add(map4);
//                            }
//                            objectMap1.put("course", mapList3);
//                        } else {
//                            objectMap1.put("course", mapList3);
//                        }
                        objectMap.put("data", objectMap1);
                        objectMap.put("roleId", shiroUserRole1.getRoleId());
                        objectMap.put("token", DigestUtils.md5Hex(teacherData.getTeacherid() + teacherData.getTeacherpassword() + shiroUserRole1.getRoleId()));
                    } else if (shiroUserRole2 != null) {//课程组长
                        Teacher teacher = teacherService.selectByPrimaryKeyo(id);
                        List<Map> mapList3 = new ArrayList<Map>();
                        Map<String, Object> map3 = new HashMap<String, Object>();
                        Map<String, Object> map4 = new HashMap<String, Object>();
                        List<Map> mapList4 = new ArrayList<Map>();
                        List<Course> courseList1 = courseService.selectCourseByCollegeC(teacher.getTeachercollege());
                        if (courseList1 != null && courseList1.size() > 0) {
                            Course course1;
                            for (int j = 0; j < courseList1.size(); j++) {
                                Map<String, Object> map5 = new HashMap<String, Object>();
                                course1 = courseList1.get(j);
                                map5.put("courseName", course1.getCoursename());
                                map5.put("courseId", course1.getCourseid());
                                mapList4.add(map5);
                            }
                        }
                        map3.put("courseList", mapList4);
                        map3.put("courseCollegeName", teacher.getTeachercollege());
                        map4.put("courseCollege", map3);
                        mapList3.add(map4);
                        objectMap1.put("course", mapList3);
                        objectMap.put("data", objectMap1);
                        objectMap.put("roleId", shiroUserRole2.getRoleId());
                        objectMap.put("token", DigestUtils.md5Hex(teacherData.getTeacherid() + teacherData.getTeacherpassword() + shiroUserRole2.getRoleId()));
                    }
                    objectMap.put("leadId", teacherData.getTeacherid());
                    objectMap.put("leadName", teacherData.getTeachername());
                    logController.logManage(id + ":登录了领导端", id);
                } catch (AuthenticationException e) {
                    token.clear();
                    objectMap.put("code", 201);
                    objectMap.put("message", "登录失败");
                }
            } else {
                objectMap.put("code", 203);
                objectMap.put("message", "此用户无权限进入领导端");
            }
        } else {
            objectMap.put("code", 202);
            objectMap.put("message", "没有此角色");
        }
        return objectMap;
    }


    @RequestMapping(value = "/loginOut")
    public synchronized String loginOut(HttpServletRequest request) {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

}
